<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>刮刮卡</title>
</head>
<style>
    * {
        margin: 0px;
        padding: 0px;
    }

    canvas {
        background: url("./images/bg.jpg") left top no-repeat;
        background-size: 100% 100%;
    }
</style>

<body>
    <canvas id="myCanvas"></canvas>
</body>

</html>
<script>
    //获取画布
    var canvas = document.getElementById('myCanvas');
    // 设置画布宽高
    canvas.width = 400
    canvas.height = 800
    // 画布上下文
    var ctx = canvas.getContext('2d');
    // 画布填充
    ctx.fillStyle = 'rgba(167, 167, 167)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fill();
    //标记用户是否正在擦除
    var isErasing = false;

    //监听canvas的鼠标事件
    canvas.addEventListener("mousedown", () => {
        isErasing = true;
    })
    canvas.addEventListener("mouseup", () => {
        isErasing = false;
    })
    canvas.addEventListener("mousemove", (e) => {
        if (isErasing) {
            var x = e.offsetX;
            var y = e.offsetY;
            var radius = 20;

            ctx.beginPath();
            //绘制圆形
            ctx.arc(x, y, radius, 0, 2 * Math.PI);
            // 将圆形与canvas上的元素混合
            ctx.globalCompositeOperation = "destination-out";
            ctx.fill();
        }
    })
</script>